package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    //拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取session中的用户信息
        Employee employee = (Employee) request.getSession().getAttribute(Constant.SESSION_EMPLOYEE);
        //如果是空的  按照固定格式返回给前端
        if (employee == null) {
            //写一个code 为o  返回错误信息为前端规定值的 ResultInfo
            ResultInfo notlogin = ResultInfo.error("NOTLOGIN");
            //吧ResultInfo转成json形式
            String json = JSON.toJSONString(notlogin);
            //传给前端
            response.getWriter().write(json);
            //登录失败
            return false;
        }

        // 存储当前线程
        EmployeeHolder.set(employee);
        //如果有session 登录成功
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }

}
